package websocket

import (
	"context"
	"encoding/json"
	"log"
	"time"

	order "gateway/basic/proto/orderproto"
)

// OrderNotifier 订单通知器
type OrderNotifier struct {
	hub         *Hub
	orderClient order.OrderClient
}

// NewOrderNotifier 创建订单通知器
func NewOrderNotifier(hub *Hub, orderClient order.OrderClient) *OrderNotifier {
	return &OrderNotifier{
		hub:         hub,
		orderClient: orderClient,
	}
}

// NotifyOrderUpdate 通知订单更新
func (n *OrderNotifier) NotifyOrderUpdate(orderInfo *order.OrderInfo) {
	orderUpdate := OrderUpdate{
		OrderID:       orderInfo.Id,
		OrderNo:       orderInfo.OrderNo,
		Status:        orderInfo.OrderStatus,
		PaymentStatus: orderInfo.PaymentStatus,
		TotalAmount:   orderInfo.TotalAmount,
		UpdatedAt:     orderInfo.UpdatedAt,
	}

	message := Message{
		Type:    "order_update",
		Data:    orderUpdate,
		OrderID: orderInfo.Id,
	}

	messageData, err := json.Marshal(message)
	if err != nil {
		log.Printf("序列化订单更新消息失败: %v", err)
		return
	}

	// 发送给相关用户（租客和房东）
	userIDs := []string{orderInfo.TenantId, orderInfo.LandlordId}
	for _, userID := range userIDs {
		if userID != "" {
			n.hub.SendToUser(userID, messageData)
		}
	}

	log.Printf("已通知订单更新: %s", orderInfo.OrderNo)
}

// NotifyOrderCreated 通知订单创建
func (n *OrderNotifier) NotifyOrderCreated(orderInfo *order.OrderInfo) {
	orderUpdate := OrderUpdate{
		OrderID:       orderInfo.Id,
		OrderNo:       orderInfo.OrderNo,
		Status:        orderInfo.OrderStatus,
		PaymentStatus: orderInfo.PaymentStatus,
		TotalAmount:   orderInfo.TotalAmount,
		UpdatedAt:     orderInfo.CreatedAt,
	}

	message := Message{
		Type:    "order_created",
		Data:    orderUpdate,
		OrderID: orderInfo.Id,
	}

	messageData, err := json.Marshal(message)
	if err != nil {
		log.Printf("序列化订单创建消息失败: %v", err)
		return
	}

	// 发送给相关用户
	userIDs := []string{orderInfo.TenantId, orderInfo.LandlordId}
	for _, userID := range userIDs {
		if userID != "" {
			n.hub.SendToUser(userID, messageData)
		}
	}

	log.Printf("已通知订单创建: %s", orderInfo.OrderNo)
}

// NotifyOrderStatusChange 通知订单状态变更
func (n *OrderNotifier) NotifyOrderStatusChange(orderInfo *order.OrderInfo, oldStatus int32) {
	statusChange := map[string]interface{}{
		"order_id":     orderInfo.Id,
		"order_no":     orderInfo.OrderNo,
		"old_status":   oldStatus,
		"new_status":   orderInfo.OrderStatus,
		"updated_at":   orderInfo.UpdatedAt,
	}

	message := Message{
		Type:    "order_status_change",
		Data:    statusChange,
		OrderID: orderInfo.Id,
	}

	messageData, err := json.Marshal(message)
	if err != nil {
		log.Printf("序列化订单状态变更消息失败: %v", err)
		return
	}

	// 发送给相关用户
	userIDs := []string{orderInfo.TenantId, orderInfo.LandlordId}
	for _, userID := range userIDs {
		if userID != "" {
			n.hub.SendToUser(userID, messageData)
		}
	}

	log.Printf("已通知订单状态变更: %s (状态: %d -> %d)", orderInfo.OrderNo, oldStatus, orderInfo.OrderStatus)
}

// NotifyPaymentUpdate 通知支付更新
func (n *OrderNotifier) NotifyPaymentUpdate(orderInfo *order.OrderInfo) {
	paymentUpdate := map[string]interface{}{
		"order_id":       orderInfo.Id,
		"order_no":       orderInfo.OrderNo,
		"payment_status": orderInfo.PaymentStatus,
		"paid_amount":    orderInfo.PaidAmount,
		"total_amount":   orderInfo.TotalAmount,
		"updated_at":     orderInfo.UpdatedAt,
	}

	message := Message{
		Type:    "payment_update",
		Data:    paymentUpdate,
		OrderID: orderInfo.Id,
	}

	messageData, err := json.Marshal(message)
	if err != nil {
		log.Printf("序列化支付更新消息失败: %v", err)
		return
	}

	// 发送给相关用户
	userIDs := []string{orderInfo.TenantId, orderInfo.LandlordId}
	for _, userID := range userIDs {
		if userID != "" {
			n.hub.SendToUser(userID, messageData)
		}
	}

	log.Printf("已通知支付更新: %s", orderInfo.OrderNo)
}

// StartOrderMonitoring 启动订单监控
func (n *OrderNotifier) StartOrderMonitoring(ctx context.Context) {
	ticker := time.NewTicker(30 * time.Second) // 每30秒检查一次
	defer ticker.Stop()

	for {
		select {
		case <-ctx.Done():
			log.Println("订单监控已停止")
			return
		case <-ticker.C:
			// 这里可以实现定期检查订单状态的逻辑
			// 例如检查是否有超时未支付的订单等
			n.checkOrderTimeouts()
		}
	}
}

// checkOrderTimeouts 检查订单超时
func (n *OrderNotifier) checkOrderTimeouts() {
	// 这里可以实现检查超时订单的逻辑
	// 例如发送提醒消息给用户
	log.Println("检查订单超时...")
}
